package net_rpc

import (
	"fmt"
	"net"
	"net/rpc"
	"time"
)

type TimeServer int

func (me *TimeServer) GetTime(_ int, t *int64) error {
	*t = time.Now().UnixNano()
	return nil
}

func (me *TimeServer) Serve(port int) error {
	addy, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("0.0.0.0:%d", port))
	if err != nil {
		return err
	}

	err = rpc.Register(me)
	if err != nil {
		return err
	}

	inbound, err := net.ListenTCP("tcp", addy)
	if err != nil {
		return err
	}
	go rpc.Accept(inbound)
	return nil
}
